package xsign

import (
	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/optional/xlog"
	"gitee.com/xiaoyutab/xgotool/xerror"
)

// 获取用户某批次的签到详情表
//
//	sid	签到批次ID
//	uid	用户ID
func User(sid, uid uint) (*SignUser, error) {
	if sid == 0 || uid == 0 {
		return nil, xerror.New("所属批次/用户不能为空")
	}
	cache_key := xcache.Key("xsign.user", sid, uid)
	u := SignUser{}
	if xcache.Exists(cache_key) {
		if err := xcache.GetStruct(cache_key, &u); err == nil {
			return &u, nil
		}
	}
	if _default.DB == nil {
		return nil, xerror.New("数据库未连接")
	}
	// 读取数据库
	err := _default.DB.Table(_default.SignUserTable).Where("uid", uid).Where("sid", sid).Order("id ASC").Find(&u).Error
	if err != nil {
		return nil, xlog.AE("用户签到数据查询失败", err)
	}
	if u.Id == 0 {
		// 没有找到用户批次数据的话，直接创建新的批次信息
		_, err := Info(sid)
		if err != nil {
			return nil, err
		}
		u.PreDate = "1970-01-01"
		u.Sid = sid
		u.Uid = uid
		err = _default.DB.Table(_default.SignUserTable).Create(&u).Error
		if err != nil {
			return nil, xlog.AE("用户签到数据插入失败", err)
		}
	}
	xcache.SetStruct(cache_key, u)
	return &u, nil
}
